package com.maikang.exammall.api;

import com.maikang.exammall.entity.Package;
import com.maikang.exammall.entity.UserContext;
import com.maikang.exammall.entity.dto.*;
import com.maikang.exammall.exception.BadRequestException;
import com.maikang.exammall.service.PackageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.web.bind.annotation.*;

import static com.maikang.exammall.entity.constant.ApiCacheKeyConstant.packageApiKey;
import static org.apache.commons.lang3.ObjectUtils.isEmpty;

@RestController
@RequiredArgsConstructor
@Log4j2
@RequestMapping("/api/packages")
public class PackageController {

    final private PackageService service;

    @PostMapping(value = "/search")
    @Cacheable(value = packageApiKey, key = "'findAll:payload:'+#findAllRequest.conditions.hashCode()+#findAllRequest.pageable.hashCode()+#findAllRequest.conditions.hospital.hashCode()")
    public ResponseDTO<Iterable<Package>> findAll(@RequestBody FindAllRequest<Package> findAllRequest) {
        if (findAllRequest == null || isEmpty(findAllRequest.getPageable())) {
            throw new BadRequestException("page is requird");
        }
        Iterable<Package> ret = this.findAll(findAllRequest.getConditions(), findAllRequest.getPageable().getPageable());
        return ResponseDTO.ok(ret);

    }

    protected Iterable<Package> findAll(Package pkg, Pageable pageable) {
        Slice<Package> all = service.findAll(pkg, pageable);
        return new SlicedContent<>(all);
    }


    @GetMapping("/{id}")
    @Cacheable(value = packageApiKey, key = "'findByIdOrNull:id:'+#id")
    public ResponseDTO<PackageDetailDTO> findByIdOrNull(@PathVariable("id") Long id) {
        PackageDetailDTO detail = service.findDetailById(id);
        return ResponseDTO.ok(detail);
    }

    @GetMapping
    @Cacheable(value = packageApiKey, key = "'findByName:name:'+#name+#cityId")
    public ResponseDTO<HospitalOrPkgDTO> findByNameAndCityId(@RequestParam("hospitalOrPkgName") String name, @RequestParam(value = "cityId", required = false) Long cityId) {
        return ResponseDTO.ok(service.findByName(name, cityId));
    }

    @GetMapping("/{id}/share_img")
    public ResponseDTO<SharePackageDTO> sharePackagePic(@PathVariable("id") Long id) {
        return ResponseDTO.ok(service.sharePackage(id, UserContext.getUserId()));
    }
}
